<?php


namespace app\admin\controller;

use app\models\CampusModel;
use app\models\CompanyModel;
use app\models\CourseModel;
use app\models\DepartmentModel;
use app\models\DictionaryModel;
use app\models\RegionalModel;
use app\models\TeacherModel;
use app\models\UserModel;

class Teacher extends Common
{



    /**
     * 用户管理模型.
     *
     *  @var UserModel
     */
    protected $userModel;

    /**
     * 区域管理模型.
     *
     *  @var RegionalModel
     */
    protected $regionalModel;

    /**
     * 部门管理模型.
     *
     * @var DepartmentModel
     */
    protected $departmentModel;

    /**
     * 字典管理模型.
     *
     * @var DictionaryModel
     */
    protected $dictionaryModel;

    /**
     * 校区管理模型.
     *
     * @var CampusModel
     */
    protected $campusModel;

    /**
     * CourseModel 课程模型.
     *
     * @var CourseModel
     */
    protected $courseModel;

    /**
     * 教师管理模型.
     *
     * @var TeacherModel
     */
    protected $teacherModel;

	/**
	 * 集团管理模型.
	 *
	 * @var CompanyModel
	 */
	protected $companyModel;


    /**
     * 教师管理.
     *
     * @throws \think\exception\DbException
     *
     * @return mixed
     */
    public function lists()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $campus = $this->teacherModel->getTeachertLists($param);
            $this->success('success', '', $campus, 0);
        }

		return $this->fetch('',
			[
				'type'=>get_current_type(),
				'company_id'=>get_current_company_id()
			]
		);
    }

	/**
	 * 选择集团
	 * modify by Small Y
	 *
	 * @return mixed
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function company()
	{
		if ($this->request->isAjax()) {
			$company_id = input('company_id');
			$this->success('success', url('Teacher/teacher_add', ['company_id' => $company_id]), '', 0);
		}
		$where = [];
		$where['status'] = 1;

        /*************过滤掉未分配系统账号的集团*************/
        $user_result = $this->userModel->where(['wtype' => 2])->select();
        $company_user_arr = [];
        foreach ($user_result as $key => $value){
            $company_user_arr[] = $value['company_id'];
        }
        $company_user_arr = array_unique($company_user_arr);
        $company_user_str = implode(',',$company_user_arr);
        $where['id'] = ['in',$company_user_str];

		$company = $this->companyModel->where($where)->select();

		return $this->fetch('', [
			'company' => $company
		]);
	}

	/**
	 * 添加老师
	 * modify by Small Y
	 *
	 * @return mixed
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
    public function teacher_add()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            $data['teacher_department'] = $this->departmentModel->get(['id' => $data['department_id']])['department_name']; //部门名称
            $data['teacher_subject'] = $this->dictionaryModel->get(['id' => $data['subject_id']])['name']; //科目
            $data['teacher_grade'] = $this->dictionaryModel->get(['id' => $data['grade_id']])['name']; //年级

            if($this->teacherModel->get(['phone' => $data['phone'], 'campus_id' => $data['campus_id']])){
                $this->error('该校区已经存在该老师', null, '', 1);
            }

            if (!$this->teacherModel->save($data)) {
                $this->error('添加老师失败', null, '', 1);
            }
            $this->success('添加成功', url('Teacher/lists'), '', 1);
        }
		$where = [];
		if(get_current_type() == 4 || get_current_type() == 5){
			$where['id'] = get_current_campus_id();
		}elseif (get_current_type() == 2 || get_current_type() == 3){
			$where['id'] = ['in',get_current_campus_id()];
		}
		if(get_current_type() == 1){
			$company_id = input('company_id');
		}else{
			$company_id = get_current_company_id();
		}
		$where['company_id'] = $company_id; //集团ID


        /***********区域**********/
        $regional_result = $this->regionalModel->select();
        $regional_arr =[];
        foreach ($regional_result as $key => $value){
            $regional_arr[$value['id'].''] = $value['regional_name'];
        }
        /*****************************/

        $campus = $this->campusModel->where($where)->select();  //校区

        if(get_current_type() == 1){  //超级管理员
            foreach ($campus as $key => $value) {
                $value['campus_name'] = $value['campus_name'] . '【' . $regional_arr[$value['regional_id'] . ''] . '】';
            }
        }

        $department = $this->departmentModel->where(['company_id'=>$company_id,'status'=>1])->select(); //部门
        $this->dictionary(); //年级

        return $this->fetch('',['campus' => $campus, 'department' => $department]);
    }


    /**
     * 编辑教师名称.
     *
     * @return mixed
     */
    public function teacher_edit()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            if (!$this->teacherModel->save($data, ['id' => $data['id']])) {
                $this->error('编辑名称失败', null, '', 1);
            }
            $this->success('编辑成功', url('Teacher/lists'), '', 1);
        }
    }

    /**
     * 导入老师表格.
     *
     * @return mixed
     */
    public function teacher_excel()
    {

        try {
            if (request()->isPost()){
                $file = request()->file('file');
                if($file->getInfo()['error'] == 0){
                    $filename = $file->getInfo()['name'];
                    $file_type = explode(".",$filename)[1];
                    if(strcasecmp($file_type,"Xlsx")== 0 || strcasecmp($file_type,"Xls") == 0
                        || strcasecmp($file_type,"Xml") == 0 || strcasecmp($file_type,"Ods") == 0
                        || strcasecmp($file_type,"Slk") == 0 || strcasecmp($file_type,"Gnumeric") == 0
                        || strcasecmp($file_type,"Html") == 0 || strcasecmp($file_type,"Csv") == 0){
                        $filename = 'Import_teacher_excel.'.$file_type;
                        $file->move(ROOT_PATH . 'public',$filename); //上传后的文件名
                        $excelData = readExcelFile(ROOT_PATH . 'public/'.$filename); //读表
                        if ($excelData != null) {
                            if(is_file(ROOT_PATH . 'public/'.$filename) && unlink(ROOT_PATH . 'public/'.$filename)){
                                //插入数据库
                                $data = [];

                                foreach ($excelData as $key => $value){
                                    $opt['teacher_name']= $value[0];

                                    $res_phone = $this->teacherModel->get(['phone' => $value[5]]);
                                    if($res_phone){
                                        continue;
                                    }

                                    $res_department = $this->departmentModel->get(['department_name' => $value[1]]); //部门
                                    if(!$res_department){
                                            continue;
                                    }
                                    $opt['teacher_department']= $value[1];
                                    $opt['department_id'] = $res_department['id']; //部门ID


                                    $res_course = $this->dictionaryModel->get(['name' => $value[2]]);  //科目

                                    if(!$res_course){
                                        continue;
                                    }

                                    $opt['teacher_subject']= $value[2];
                                    $opt['subject_id']=$res_course['id']; //科目d

                                    $res_grades = $this->dictionaryModel->get(['name' => $value[3], 'type' => 1]); //年级名称

                                    if(!$res_grades){
                                        continue;
                                    }
                                    $opt['teacher_grade']= $value[3];
                                    $opt['grade_id'] = $res_grades['id']; //年级ID


                                    $res_campus = $this->campusModel->get(['campus_name' => $value[4]]);

                                    if(!$res_campus){
                                        continue;
                                    }

                                    $opt['campus_id']= $res_campus['id'];  //校区ID
                                    $opt['phone'] = $value[5]; //电话

                                    $data[] = $opt;
                                }


                                if(count($data) > 0){
                                    $this->teacherModel->saveAll($data);
                                }



                                return ['code' => 0, 'data' => $excelData, 'name' => $filename, 'size'=>$file->getInfo()['size']];
                            }

                        }
                    }
                }



            }

        } catch (\Exception $e) {
            return ['code' => 1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 删除教师.
     *
     * @return mixed
     */
    public function teacher_del()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            if (!$this->teacherModel->where(['id' => input('id')])->delete()) {
                $this->error('删除教师失败', null, '', 1);
            }
            $this->success('删除成功', url('Teacher/lists'), '', 1);
        }
    }

    /**
     * 更改教师状态.
     *
     * @return mixed
     */
    public function teacher_status()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            if (1 == $data['status']) {
                $msg = '启用';
            } else {
                $msg = '禁用';
            }
            if (!$this->teacherModel->save($data, ['id' => $data['id']])) {
                $this->error($msg.'教师失败', null, '', 1);
            }
            $this->success($msg.'成功', '', '', 1);
        }
    }

    /**
     * 通过校区名称获取老师列表.
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getByCampusId()
    {
        $campusId = input('campus_id');
        if ($campusId) {
            $teacher = $this->teacherModel->getByCampusId($campusId);
            $this->success('success', '', $teacher, 0);
        }
        $this->error('无数据');
    }

    /**
     * 通过校区名称获取班主任列表.
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getByCampusMasterId()
    {
        $campusId = input('campus_id');
        if ($campusId) {
            $teacher = $this->userModel->where(['campus_id' => $campusId, 'group_type' => 4])->select();
            $this->success('success', '', $teacher, 0);
        }
        $this->error('无数据');
    }

    /**
     * 通过部门名称获取老师列表.
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getByDepartmentId()
    {
        $teacher = $this->teacherModel->getByDepartmentId(input('post.'));
        $this->success('success', '', $teacher, 0);
        $this->error('无数据');
    }

    /**
     * 通过年级名称获取老师列表.
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getByGradeId()
    {
		$teacher = $this->teacherModel->getByGradeId(input('post.'));
		$this->success('success', '', $teacher, 0);
        $this->error('无数据');
    }

    /**
     * 通过科目名称获取老师列表.
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getBySubjectId()
    {
		$teacher = $this->teacherModel->getBySubjectId(input('post.'));
		$this->success('success', '', $teacher, 0);
        $this->error('无数据');
    }

    /**
     *  实例化.
     */
    protected function _initialize()
    {
        parent::_initialize();
        $this->teacherModel = new TeacherModel();
        $this->departmentModel = new DepartmentModel();
        $this->campusModel = new CampusModel();
        $this->courseModel = new CourseModel();
        $this->companyModel = new CompanyModel();
        $this->regionalModel = new RegionalModel();
        $this->userModel = new UserModel();
    }
}